
<template>
    <div class="table-filter-comp">
        <el-popover
            placement="bottom-start"
            trigger="hover"
            popper-class="table-filter-drop-box">
            <template #reference>
                <div class="table-filter-box">
                    <div class="filter-cont">
                        <div class="img-wrap">
                            <el-image class="filter-img show-img" :src="filterImg" fit="contain" />
                            <el-image class="filter-img hover-img" :src="filterhoverImg" fit="contain" />
                            <el-image class="filter-img active-img" :src="filteractiveImg" fit="contain" />
                        </div>

                        <div class="img-wrap arrow-box">
                        <el-icon class="arrow-img"><CaretBottom /></el-icon>
                        </div>
                    </div>
                </div>
            </template>

            <div class="table-filter-cont-box">
                <!-- <el-checkbox-group v-model="list">
                    <div class="filter-chbox-wrap">
                        <el-checkbox class="filter-chbox-item" label="Option A" />
                        <el-checkbox class="filter-chbox-item" label="The main functions" />
                        <el-checkbox class="filter-chbox-item" label="Option C" />
                    </div>
                </el-checkbox-group> -->
                <div class="filter-chbox-wrap">
                    <!-- <el-checkbox v-for="colItem in dataObj.colList" 
                        :key="'fi_ch_' + colItem.dataCode" 
                        v-model="colItem.isShow" 
                        class="filter-chbox-item" @change="toCnage">
                        <span v-lang="{lang: controlSto.language, lgid: colItem.langkey, list: controlSto.langList}"></span>
                    </el-checkbox> -->
                    <el-checkbox v-for="colItem in dataObj.colList" :key="'fi_ch_' + colItem.dataCode" 
                        v-model="colItem.isShow" 
                        class="filter-chbox-item" 
                        :label="delaLable(colItem)" @change="toCnage"/>
                </div>
            </div>
        </el-popover>
    </div>




    <!-- <div class="table-filter-comp">
        <div class="filter-cont">
            <div class="img-wrap">
                <el-image class="filter-img show-img" :src="filterImg" fit="contain" />
                <el-image class="filter-img hover-img" :src="filterhoverImg" fit="contain" />
                <el-image class="filter-img active-img" :src="filteractiveImg" fit="contain" />
            </div>

            <div class="img-wrap arrow-box">
            <el-icon class="arrow-img"><CaretBottom /></el-icon>
            </div>
        </div>
    </div> -->

</template>

<script setup>
    import { ref, reactive, toRefs, onBeforeMount, computed, watch } from 'vue'
    import { debounce, cloneDeep, concat, filter, uniqBy } from 'lodash'
    import { controlStore } from '@/stores/control'
    import { geneMathHash, langTxt } from '@/utils/util'
    
    import filterImg from '@/assets/img/filter.png'
    import filterhoverImg from '@/assets/img/filter-hover.png'
    import filteractiveImg from '@/assets/img/filter-active.png'

    const emitter = defineEmits(['onChg']);
    const props = defineProps({
        column: {
            type: Array,
            default: () => []
        },
        filterKey: {
            type: [Number, String],
            default: 1
        },
    });
    const { column, filterKey } = toRefs(props);

    let chgDebounce = null;

    const controlSto = controlStore();
    const list = ref([]);

    const dataObj = reactive({
        colList: [],
        headList: [],
        actList: [],
        colIdxObj: {},
    });

    const configKey = computed(()=> {
        let arr = column.value.map(i => i.dataCode);
        return geneMathHash(arr.join(','));
    });

    onBeforeMount(()=> {
        initDebounce();
		// getCol();
    });

    const initDebounce = () => {
        chgDebounce = debounce((e) => {
            dealReturnList();
        }, 400);
    };

    const delaLable = (item) => {
        let str = '';
        if(item.langkey) {
            if(item.id < 0) {
                str = langTxt(controlSto.language, item.langkey);
            } else {
                str = langTxt(controlSto.language, item.langkey, controlSto.langList);
            }
        }
        return str;
	};
	const getCol = () => {
        if(column.value && column.value.length > 0) {
            let locStr = localStorage.getItem('colsetting_' + filterKey.value);
            if(!locStr) {
                let arr = [];
                column.value.forEach(i => {
                    if(i.dataCode == 'index' || i.dataCode == 'selection' || i.dataCode == 'act') {
                        
                    } else {
                        arr.push(i.dataCode);
                    }
                });
                //去重，locStr中有很多重复的数据
                if(arr.length) {
                    const setLocStr = new Set(arr)
                    dealCol([...setLocStr].join(','));
                }
            } else if(locStr == '-1') {
                dealCol('');
            } else {
                dealCol(locStr);
            }
        }
    };

    const dealCol = (colRes) => {
        if(!colRes.length) return;
        const setLocStr = new Set(colRes.split(','));
        let list = [...setLocStr];
        let colStr = 'aaa' + list.join('aaa') + 'aaa';

        let headList = [];
        let actList = [];

        let lockList = [];
        let tailList = [];
        let colIdxObj = {};

        let colArr = cloneDeep(column.value);


        // 判断是不是新 columnConfig
        let colConfStr = 'aaa';
        colArr.forEach((i, index) => {
            colConfStr += i.dataCode + 'aaa';
        });
        let isNew = false;
        list.forEach(i => {
            if(colConfStr.indexOf('aaa' + i + 'aaa') < 0) {
                isNew = true;
            }
        });
        // ---end--判断是不是新 columnConfig


        colArr.forEach((i, index) => {
            if(i.dataCode == 'index' || i.dataCode == 'selection') {
                headList.push(i);
            } else if(i.dataCode == 'act') {
                actList.push(i);
            } else if(i.isLock || isNew) {
                i.isShow = true;
                lockList.push(i);
            } else if(colStr.indexOf('aaa' + i.dataCode + 'aaa') < 0) {
                tailList.push(i);
            } else {
                i.isShow = true;
            }
            colIdxObj[i.dataCode] = index;
        });

        dataObj.headList = headList;
        dataObj.actList = actList;
        dataObj.colIdxObj = colIdxObj;


        let lockListStr = 'aaa' + lockList.join('aaa') + 'aaa';
        let midList = [];
        list.forEach(i => {
            if(lockListStr.indexOf('aaa' + i + 'aaa') < 0) {
                midList.push(colArr[colIdxObj[i]])
            }
        });

        let resList = concat(lockList, midList, tailList);
        
        dataObj.colList = filter(resList, (i)=>{ return !!i});
        dealReturnList();
    };

    const dealReturnList = () => {
        let midList = [];
        let colArr = cloneDeep(column.value);
        dataObj.colList.forEach(i => {
            if(i && i.isShow) {
                midList.push(colArr[dataObj.colIdxObj[i.dataCode]])
            }
        });
        // console.log(midList, '-----}}}}}}', filterKey.value)
        if(midList.length == 0) {
            localStorage.setItem('colsetting_' + filterKey.value, '-1');
        } else {
            let midArr = midList.map(i => i.dataCode);
            localStorage.setItem('colsetting_' + filterKey.value, midArr.join(','));
        }
        midList = uniqBy(midList, 'dataCode');
        let resArr = concat(dataObj.headList, midList, dataObj.actList);

        // console.log('resArr--------------f---', resArr);
        emitter('onChg', resArr);
    };


    const toCnage = () => {
        chgDebounce && chgDebounce();
    };
    


    // toSave() {
    //     this.dealReturnList();
    // }

    watch(() => configKey.value, (nv, ov) => {
		if(nv != ov) {
            getCol();
		}
	});
    

</script>


<style lang="scss" scoped>
    .table-filter-comp {
        display: inline-block;
        .table-filter-box {
            display: inline-block;
        }
        .filter-cont {
            min-width: 44px;
            height: 32px;
            padding: 0 6px 0 8px;
            line-height: 32px;
            text-align: center;
            border: 1px solid #BC9F77;
            border-radius: 4px;
            color: #BC9F77;
            user-select: none;
            cursor: pointer;
            &:hover {
                color: #E6C896;
                .hover-img {
                    display: inline-block;
                }
                .show-img, .active-img {
                    display: none;
                }
            }
            &:active {
                color: #967846;
                .active-img {
                    display: inline-block;
                }
                .hover-img, .show-img {
                    display: none;
                }
            }
            .hover-img, .active-img {
                display: none;
            }
            .img-wrap {
                position: relative;
                display: inline-block;
                top: 2px;
                .filter-img {
                    height: 16px;
                }
            }
            .arrow-box {
                padding-left: 6px;
            }
        }
    }
</style>


<style lang="scss">
    .table-filter-drop-box {
        width: auto !important;
        padding: 0 !important;
    }
    .table-filter-cont-box {
        max-height: 260px;
        overflow-y: auto;
        .filter-chbox-wrap {
            width: 180px;
            padding: 8px 0;
            .filter-chbox-item {
                width: 168px;
                height: auto;
                padding: 8px 0;
                padding-left: 12px;
                margin-right: 0;
            }
            .el-checkbox__label {
                line-height: 16px;
                word-break: break-all;
                white-space: pre-wrap;
            }
            .el-checkbox__inner:hover {
                border-color: #BC9F77;
            }
            .el-checkbox__input.is-checked .el-checkbox__inner {
                background-color: #BC9F77;
                border-color: #BC9F77;
            }
            .el-checkbox__input.is-checked + .el-checkbox__label {
                color: #BC9F77;
            }
        }
    }
</style>